# -*- coding: utf-8 -*-
import sys, time, random
import socket
import threading
from PyQt4 import QtGui, QtCore
from httpServerUI import Ui_serverWidget
from pydoc import gui
from serverHandle import *

class httpServerGui(QtGui.QWidget, Ui_serverWidget, serResHandle):
    #定义一个信号
    txt_signal = QtCore.pyqtSignal(str)
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setupUi(self)
        serResHandle.__init__(self)
        self.setWindowIcon(QtGui.QIcon('T1.ico')) 
        #将信号连接到一个函数（槽）      
        self.txt_signal.connect(self.write_to_textbox) 
        self.httpHeaders = {}
        self.ifPrint = False
        self.ifRunTask = False
        #http返回页面，文件对话框
        self.connect(self.fileOpenToolButton, QtCore.SIGNAL('clicked()'), self.read_page_file)
        self.connect(self.reloadConfigPushButton, QtCore.SIGNAL('clicked()'), self.get_args)
        self.connect(self.startPushButton, QtCore.SIGNAL('clicked()'), self.if_run_task)
        #确定程序的打印是否显示到界面，做到实时生效
        self.connect(self.ifPrintCheckBox, QtCore.SIGNAL('stateChanged(int)'), self.change_ifPrint)
    def get_args(self):
        self.listenPort = int(self.listenPortLineEdit.text())
        self.ifPrint = self.ifPrintCheckBox.isChecked()
        self.latency = self.latencyDoubleSpinBox.value()
        self.resCode = int(self.respondCodeComboBox.currentText())
        if self.pageTypeRadioButton.isChecked():
            self.pageSize = int(self.defaultPageSizeLineEdit.text())
        elif self.pageTypeRadioButton_2.isChecked():
            #self.read_page_file()
            self.pageSize = len(self.pageFile)
        self.keepAliveTime = int(self.KeepAliveTimeSpinBox.value())
        self.parse_custom_headers()
    def parse_custom_headers(self):
        #解析自定义头部框中的内容，得到自定义头部的内容，为一个字典类型
        tempstr = str(self.customHeaderTextEdit.toPlainText())
        if tempstr:
            for l in tempstr.split('\n'):
                if l.find(':') != -1:
                    self.httpHeaders[l.split(':')[0]] = l.split(':')[1].strip('\n').strip() 
    def read_page_file(self):
        if self.pageTypeRadioButton_2.isChecked():
            filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
                        '')
            try:
                f = open(filename)
            except:
                QtGui.QMessageBox.information(self , "Information" ,    
                                    u"确保文件路径中不含中文")
                self.pageFile = ''
                return
            self.pageFileLineEdit.setText(repr(filename).split('/')[-1][0:-2])
            self.pageFile = f.read()
            f.close()
    def write(self, s):
        self.txt_signal.emit(s)        
    #修饰后，可以不阻塞地接收信号，后面函数为对信号的处理
    @QtCore.pyqtSlot(str)
    def write_to_textbox(self, text):
        try:
            s = str(text)
        except:
            self.printTextEdit.append(text)
            return
        if s == '\n':
            pass
        else: 
            self.printOutTextEdit.append(text)
    def if_run_task(self):
        #是否执行任务，startPushButton有两种状态： “启动”和“停止”
        if self.ifRunTask == False:
            self.startPushButton.setText(u"停止")
            self.printOutTextEdit.setText('')
            self.run_task()
            self.ifRunTask = True
        elif self.ifRunTask == True:
            self.startPushButton.setText(u"启动")
            self.stop_task()
            self.ifRunTask = False
    def change_ifPrint(self):
        if self.ifPrintCheckBox.isChecked():
            self.ifPrint = True
        else:
            self.ifPrint = False
    def run_task(self):
        self.ifPrint = True
        self.get_args()
        threading.Thread(target = self.run).start()
    def stop_task(self):
        self.stop()
        #sock连接，防止server socket阻塞在accept()而无法停止
        threading.Thread(target = self.sock_test).start()
        threading.Thread(target = self.sock_test6).start()
    def sock_test(self):
        try:
            test = socket.create_connection(('127.0.0.1', self.listenPort))
        except:
            return
        test.close()
    def sock_test6(self):        
        try:
            test6 = socket.create_connection(('::1', self.listenPort))
        except:
            return
        test6.close()
def main():
    app = QtGui.QApplication(sys.argv)
    serverGui = httpServerGui()
    serverGui.show()
    sys.stdout = serverGui
    sys.exit(app.exec_())
    

if __name__=='__main__':
    main()